﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Collections.ObjectModel;
using System.Collections;

namespace CitrixPVSWrapper
{

    [System.Management.Automation.Cmdlet("RunWithReturn", "PvsCreateMaintenanceVersion", SupportsShouldProcess = true)]
    public class Run_PvsCreateMaintenanceVersion : System.Management.Automation.PSCmdlet
    {

        [Parameter(ParameterSetName = "DiskLocator", Mandatory = true)]
        public PvsDiskLocator DiskLocator;

        [Parameter(ParameterSetName = "DiskLocatorId", ValueFromPipelineByPropertyName = true, Mandatory = true)]
        public string DiskLocatorId;

        [Parameter(ParameterSetName = "DiskLocatorName", Mandatory = true)]
        [Parameter(ParameterSetName = "DiskLocatorName-SiteName", Mandatory = true)]
        [Parameter(ParameterSetName = "DiskLocatorName-SiteId", Mandatory = true)]
        [Parameter(ParameterSetName = "DiskLocatorName-Site", Mandatory = true)]
        [Parameter(ParameterSetName = "DiskLocatorName-StoreName", Mandatory = true)]
        [Parameter(ParameterSetName = "DiskLocatorName-StoreId", Mandatory = true)]
        [Parameter(ParameterSetName = "DiskLocatorName-Store", Mandatory = true)]
        public string DiskLocatorName;
        
        [Parameter(ParameterSetName = "DiskLocatorName-Site", Mandatory = true)]
        public PvsSite Site;

        [Parameter(ParameterSetName = "DiskLocatorName-SiteId", Mandatory = true)]
        public string SiteId;

        [Parameter(ParameterSetName = "DiskLocatorName-SiteName", Mandatory = true)]
        public string SiteName;

        [Parameter(ParameterSetName = "DiskLocatorName-Store", Mandatory = true)]
        public PvsStore Store;

        [Parameter(ParameterSetName = "DiskLocatorName-StoreId", Mandatory = true)]
        public string StoreId;

        [Parameter(ParameterSetName = "DiskLocatorName-StoreName", Mandatory = true)]
        public string StoreName;

        protected override void ProcessRecord()
        {
            // Verbose and Debug Settings
            Boolean Verbose = this.MyInvocation.BoundParameters.ContainsKey("Verbose");
            WriteVerbose("Verbose Flag: " + Verbose);
            Boolean Debug = this.MyInvocation.BoundParameters.ContainsKey("Debug");
            WriteDebug("Debug Flag: " + Debug);

            // Collections to hold the queries and the results
            Collection<QueryDefinition> RunQueries = new Collection<QueryDefinition>();
            string TargetObject = "CreateMaintenanceVersion";

            // Build the queries based on the parameter sets
            switch (this.ParameterSetName)
            {

                case "DiskLocator":
                    {
                        RunQueries.Add(new QueryDefinition(QueryActionType.RunWithReturn, TargetObject, "DiskLocatorId=\"" + this.DiskLocator.DiskLocatorId + "\""));
                        break;
                    }

                case "DiskLocatorId":
                    {
                        RunQueries.Add(new QueryDefinition(QueryActionType.RunWithReturn, TargetObject, "DiskLocatorId=\"" + this.DiskLocatorId + "\""));
                        break;
                    }

                case "DiskLocatorName":
                    {
                        foreach (PvsDiskLocator QryDiskLocator in Get_PvsDiskLocator_Internal.Get_DiskLocatorByName(this.DiskLocatorName, Verbose))
                        { RunQueries.Add(new QueryDefinition(QueryActionType.RunWithReturn, TargetObject, "DiskLocatorId=\"" + QryDiskLocator.DiskLocatorId + "\"")); }
                        break;
                    }

                case "DiskLocatorName-Site":
                    {
                        foreach (PvsDiskLocator QryDiskLocator in Get_PvsDiskLocator_Internal.Get_DiskLocatorByNameAndSiteId(this.DiskLocatorName, this.Site.SiteId, Verbose))
                        { RunQueries.Add(new QueryDefinition(QueryActionType.RunWithReturn, TargetObject, "DiskLocatorId=\"" + QryDiskLocator.DiskLocatorId + "\"")); }
                        break;
                    }

                case "DiskLocatorName-SiteId":
                    {
                        foreach (PvsDiskLocator QryDiskLocator in Get_PvsDiskLocator_Internal.Get_DiskLocatorByNameAndSiteId(this.DiskLocatorName, this.SiteId, Verbose))
                        { RunQueries.Add(new QueryDefinition(QueryActionType.RunWithReturn, TargetObject, "DiskLocatorId=\"" + QryDiskLocator.DiskLocatorId + "\"")); }
                        break;
                    }

                case "DiskLocatorName-SiteName":
                    {
                        foreach (PvsDiskLocator QryDiskLocator in Get_PvsDiskLocator_Internal.Get_DiskLocatorByNameAndSiteName(this.DiskLocatorName, this.SiteName, Verbose))
                        { RunQueries.Add(new QueryDefinition(QueryActionType.RunWithReturn, TargetObject, "DiskLocatorId=\"" + QryDiskLocator.DiskLocatorId + "\"")); }
                        break;
                    }

                case "DiskLocatorName-Store":
                    {
                        foreach (PvsDiskLocator QryDiskLocator in Get_PvsDiskLocator_Internal.Get_DiskLocatorByNameAndStoreId(this.DiskLocatorName, this.Store.StoreId, Verbose))
                        { RunQueries.Add(new QueryDefinition(QueryActionType.RunWithReturn, TargetObject, "DiskLocatorId=\"" + QryDiskLocator.DiskLocatorId + "\"")); }
                        break;
                    }

                case "DiskLocatorName-StoreId":
                    {
                        foreach (PvsDiskLocator QryDiskLocator in Get_PvsDiskLocator_Internal.Get_DiskLocatorByNameAndStoreId(this.DiskLocatorName, this.StoreId, Verbose))
                        { RunQueries.Add(new QueryDefinition(QueryActionType.RunWithReturn, TargetObject, "DiskLocatorId=\"" + QryDiskLocator.DiskLocatorId + "\"")); }
                        break;
                    }

                case "DiskLocatorName-StoreName":
                    {
                        foreach (PvsDiskLocator QryDiskLocator in Get_PvsDiskLocator_Internal.Get_DiskLocatorByNameAndStoreName(this.DiskLocatorName, this.StoreName, Verbose))
                        { RunQueries.Add(new QueryDefinition(QueryActionType.RunWithReturn, TargetObject, "DiskLocatorId=\"" + QryDiskLocator.DiskLocatorId + "\"")); }
                        break;
                    }

            }

            // Test that we have a suitable object to perform the Run with, and build the confirmation message
            if (RunQueries.Count() == 0)
            {
                WriteError(new ErrorRecord(new InvalidOperationException("Unable to create a maintenance version using the supplied parameters"), "1", ErrorCategory.InvalidArgument, null));
            }

            // Execute the run queries
            foreach (QueryDefinition RunQuery in RunQueries)
            {
                string objectId;
                string objectName;
                string ShouldProcessMessage;

                // Check that we have a valid parameter to work with, extract the object id/name and build the ShouldProcess message
                if (RunQuery.Parameters.Where(p => p.StartsWith("DiskLocatorId")).Count() == 1)
                {
                    objectId = RunQuery.Parameters.Where(p => p.StartsWith("DiskLocatorId")).First().Split('=')[1].Replace('"', ' ').Trim();
                    if (Get_PvsDiskLocator_Internal.Get_DiskLocatorById(objectId).Count() != 1)
                    {
                        WriteError(new ErrorRecord(new InvalidOperationException(String.Format("DiskLocator Id {0} does not exist", objectId)), "2", ErrorCategory.InvalidArgument, null));
                        continue;
                    }
                    objectName = Get_PvsDiskLocator_Internal.Get_DiskLocatorById(objectId).First().DiskLocatorName;
                    ShouldProcessMessage = String.Format("Create new maintenance version for disk locator {0} with disk locator Id {1}", objectName, objectId);
                }

                else
                {
                    WriteError(new ErrorRecord(new InvalidOperationException("Query does not contain any valid targets"), "2", ErrorCategory.InvalidArgument, null));
                    continue;
                }

                // Perform the actual run and return any errors
                if (ShouldProcess(ShouldProcessMessage))
                {
                    foreach (string[] Record in PvsHelpers.ExecuteMcliQuery(RunQuery, Verbose, Debug))
                    {
                        WriteDebug("Returning Object");
                        WriteObject(PvsHelpers.Get_StringValueFromRecord("Name", Record, Verbose));
                    }
                }

            }
        }
    }
}
